const qiniu = require("qiniu");
const config = require('../../config/filestore.json');

qiniu.conf.ACCESS_KEY = config.accessKey;
qiniu.conf.SECRET_KEY = config.secretKey;

import filesizeParser from 'filesize-parser';

export const BUCKET = config.bucket;

const MAX_SIZE = filesizeParser(config.maxSize || '20m');

const putPolicy = new qiniu.rs.PutPolicy2({
  scope: config.bucket,
  fsizeLimit: MAX_SIZE,
  returnBody: `{"hash": $(etag), "w": $(imageInfo.width), "h": $(imageInfo.height)}`,
})

export function createUploadToken(){
  const token = putPolicy.token();
  return {
    url: 'http://upload.qiniu.com/',
    fieldName: 'file',
    formData: {
      token,
      accept: 'application/json',
    },
    responseType: 'json',
  };
}

export async function upload(ctx) {
  ctx.body = createUploadToken();
}

const getPolicy = new qiniu.rs.GetPolicy();

export function getDownloadUrl(key, options) {
  if (!key) {
    return null;
  }
  let url = `http://${config.domain}/${key}`;
  // return getPolicy.makeRequest(url);
  if (options && options.mode) {
    url += `?imageView2/${options.mode}`;
    const {w, h, format, inter, q, ignoreError} = options;
    if (w) {
      url += `/w/${w}`;
    }
    if (h) {
      url += `/h/${h}`;
    }
    if (format) {
      url += `/format/${format}`;
    }
    if (inter) {
      url += `/interface/${inter}`;
    }
    if (q) {
      url += `/q/${q}`;
    }
    if (ignoreError) {
      url += `/ignore-error/${ignoreError}`;
    }
  }
  return url;
}